package HelloArithmetic.Hash;


import lombok.val;

import java.sql.Array;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @program: JavaDataStructure
 * @ClassName _02ArrayHashMap
 * @description: 使用array实现哈希表
 * @author: jing
 * @create: 2025-07-22 16:24
 **/

public class _02ArrayHashMap {
    public static void main(String[] args) {
        ArrayHashMap arrayHashMap = new ArrayHashMap();
        arrayHashMap.put(1,"jing");
        arrayHashMap.put(2,"nan");
        arrayHashMap.put(3,"jing");
        //通过key获取值
        System.out.println(arrayHashMap.get(1));
        //删除
        arrayHashMap.remove(1);
        System.out.println(arrayHashMap.pairsSet());
        System.out.println(arrayHashMap.getKeys());
        System.out.println(arrayHashMap.vals());
    }
}


class Pair{
    public  int key;
    public String value;

    public Pair(int key,String value){
        this.key = key;
        this.value = value;
    }

}

class ArrayHashMap{
    private List<Pair> buckets;

    //构造函数-初始化数组
    public ArrayHashMap(){
        buckets = new ArrayList<>();
        for (int i = 0; i < 100; i++) {
            buckets.add(null);
        }
    }

    //哈希函数
    public int hashFunc(int key){
        return key%100;
    }

    //查询操作
    public String get(int key){
        int index = hashFunc(key);
        Pair pair = buckets.get(index);
        if(pair == null){
            return null;
        }
        return pair.value;
    }
    //添加操作
    public void put(int key,String value){
        Pair pair = new Pair(key, value);
        int index = hashFunc(key);
        buckets.set(index, pair);
    }

    //删除操作
    public void remove(int key){
        int index = hashFunc(key);
        buckets.set(index,null);
    }

    //获取所有键值对
    public List<Pair> pairsSet(){
        List<Pair> keyValue = new ArrayList<>();
        for(Pair pair:buckets){
            if(pair!= null){
                keyValue.add(pair);
            }
        }
        return keyValue;
    }

    //获取所有键
    public List<Integer> getKeys(){
        List<Integer> keys = new ArrayList<>();
        for(Pair pair:buckets){
            if(pair != null){
                keys.add(pair.key);
            }
        }
        return keys;
    }

    //获取所有值
    public List<String> vals(){
        List<String> values = new ArrayList<>();
        for(Pair pair:buckets){
            if(pair != null ){
                values.add(pair.value);
            }
        }
        return values;
    }

    //打印哈希表
    public void print(){
        for(Pair kv:pairsSet()){
            System.out.println(kv.key+":"+kv.value);
        }
    }
}
